<template>
  <div class="storeSalesQuery">
    <div class="ssq-top">
      <div>
        <p>店铺</p>
        <el-select
          clearable
          class="wd"
          v-model="shopName"
          @change="shopChange"
          filterable
          :disabled="jxStore"
        >
          <el-option
            v-for="item in shopList"
            :key="item.value"
            :label="item.value + '  ' + item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <p>VIP</p>
        <el-select
          clearable
          filterable
          class="wd"
          v-model="vipPhone"
          @change="Change1"
        >
          <el-option
            v-for="item in vipList"
            :key="item.value1"
            :label="item.value1 + '  ' + item.value"
            :value="item.value"
          ></el-option>
        </el-select>
        <!-- <p>型号</p>
        <el-input class="wd"></el-input> -->
        <p>主推</p>
        <el-select clearable class="wd" v-model="main" filterable>
          <el-option
            v-for="item in List"
            :key="item.value"
            :label="item.value + '  ' + item.value1"
            :value="item.value"
          ></el-option>
        </el-select>
        <p>次推</p>
        <el-select clearable class="wd" v-model="minor" filterable>
          <el-option
            v-for="item in List1"
            :key="item.value"
            :label="item.value + '  ' + item.value1"
            :value="item.value"
          ></el-option>
        </el-select>
        <p>款号</p>
        <el-input clearable class="wd" v-model="kindsNumber"></el-input>
        <!-- <el-select class="wd">
        <el-option
        v-for="item in warehouseNoList"
        :key="item.value"
        :label="item.label"
        :value="item.value">
        </el-option>
        </el-select> -->
        <p>品牌</p>
        <el-select clearable class="wd" v-model="brandedName" filterable>
          <el-option
            v-for="item in brandedList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

        <p>单据确认</p>
        <el-select
          clearable
          style="width: 100px"
          v-model="affirm"
          placeholder="请选择"
        >
          <el-option
            v-for="item in confirmList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div style="margin-top: 10px">
        <p>销售日期</p>
        <el-date-picker
          clearable
          unlink-panels
          v-model="timeData"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </div>
    </div>
    <div class="ssq-btn">
      <div>
        <el-button @click="query" type="primary" icon="el-icon-search"
          >查询</el-button
        >
        <el-button
          icon="el-icon-circle-check"
          @click="Confirm"
          :disabled="Dis || isRegular"
          >确认</el-button
        >
        <el-button
          @click="Del"
          icon="el-icon-delete"
          :disabled="Dis || isRegular"
          >删单</el-button
        >
        <el-button
          icon="el-icon-circle-plus-outline"
          @click="Supplement"
          :disabled="Dis || isRegular"
          >补单</el-button
        >
        <el-button
          @click="exportExcel"
          :disabled="isRegular"
          icon="el-icon-download"
          >导出</el-button
        >
      </div>
      <div style="display: flex">
        <div style="margin-top: 5px; display: flex">
          <div class="tip" style="background: #6bcc7b"></div>
          :已完成
          <div class="tip" style="background: #ff0000"></div>
          :未确认
          <div class="tip" style="background: #65318e"></div>
          :
          <p style="margin-right: 15px">未结账</p>
          <!-- <div class="tip" style="background:#017aff;"></div>:<p style="margin-right:15px;">调货摘要</p> -->
        </div>
        <el-checkbox v-model="checked" border>二维</el-checkbox>
      </div>
    </div>
    <div class="ssq-tab">
      <div class="tab-left">
        <el-table
          id="outTable"
          border
          :summary-method="getList"
          show-summary
          :data="aList"
          style="width: 100%"
          height="68vh"
          @row-click="rowClick"
          @row-dblclick="dbClick"
          highlight-current-row
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '26px' }"
        >
          <!-- <el-table-column type="index" label="序号" width="50"></el-table-column> -->
          <el-table-column
            prop="operator"
            label="店铺"
            min-width="120"
          ></el-table-column>
          <el-table-column label="单据状态" width="90">
            <template slot-scope="scope">
              <div style="display: flex; text-align: center">
                <div
                  class="tip1"
                  :style="{
                    background:
                      scope.row.sequenceStatus == 0
                        ? '#FF0000'
                        : scope.row.sequenceStatus == 4
                        ? '#65318E'
                        : '#6BCC7B'
                  }"
                ></div>
                <p>
                  {{
                    scope.row.sequenceStatus == 0
                      ? '未确认'
                      : scope.row.sequenceStatus == 4
                      ? '未结账'
                      : '已完成'
                  }}
                </p>
              </div>
            </template>
          </el-table-column>
          <template v-for="i in bList">
            <el-table-column
              :prop="i.prop"
              :label="i.label"
              :width="i.width"
              :key="i.prop"
            ></el-table-column>
          </template>
        </el-table>
        <div class="balance" :style="{ display: showbox }">
          <p>余额：{{ Howmany }}</p>
        </div>
      </div>
      <div class="tab-right">
        <el-table
          id="outTable"
          border
          :data="cList"
          height="68vh"
          style="width: 100%"
          highlight-current-row
          :header-cell-style="{
            background: '#f4f4f4',
            padding: 0,
            height: '40px'
          }"
          :cell-style="{ padding: 0, height: '26px' }"
        >
          <!-- <el-table-column type="index" label="序号" width="50"></el-table-column> -->
          <template v-for="i in eList">
            <el-table-column
              :prop="i.prop"
              :label="i.label"
              :width="i.width"
              :key="i.prop + Math.random()"
            ></el-table-column>
          </template>
        </el-table>
      </div>
    </div>
    <!-- 分頁 -->
    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <el-popover
          placement="top-start"
          width="120"
          max-height="100px"
          trigger="click"
        >
          <i slot="reference" class="el-icon-date">表头配置</i></el-popover
        >
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
    <new-vs
      v-if="showNew"
      :sendData="sendData"
      :clerkList="clerkList"
      :flag="showNew"
      @inpNumChange="
        () => {
          this.inpList = this.getInput()
        }
      "
      :title="title"
      :title1="title1"
      :customerNo="shopNo"
      @determine="
        () => {
          this.title1 = ''
        }
      "
      @closeNew="
        () => {
          ;(this.showNew = false), this.query(), (this.title1 = '')
        }
      "
      @saveNew="saveNew"
    ></new-vs>
  </div>
</template>

<script>
import footView from '../../../components/FootView'
import today from '../../../components/mixins/today'
import {
  getVip,
  getShopSale,
  getClerk1,
  getmoney,
  confirm,
  DeleteSell
} from '../../../network/shop'
import { getBranded } from '../../../network/branded'
import { getClient } from '../../../network/client'

import outex from '../../../components/mixins/outexp'
import newVs from '../StoreSales/childComp/newVs'
import enterUp from '../../../components/mixins/enterUp'

import cookieFn from '../../../components/mixins/cookieFn'

export default {
  name: 'store_sales_query',
  mixins: [today, outex, enterUp, cookieFn],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent' + '=([^;]+)'))
    this.operatorVal = operatorVal ? operatorVal[1] : null
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null

    this.inpList = this.getInput()
    if (localStorage.getItem('whatState') == '直营') {
      this.isRegular = false
    } else {
      this.isRegular = true
    }
    this.timeData = [this.getLastWeek(), this.getNowTime()]
    this.bList = this.bList1
    this.eList = this.eList1

    // 品牌公司查品牌
    getBranded().then((res) => {
      res.data.data.forEach((e) => {
        this.brandedList.push({ value: e.name, label: e.name })
      })
    })

    //客户 -> 店铺
    getClient().then((res) => {
      let list = res.data.data
      list.forEach((e) => {
        if (e.stop != 1) {
          this.shopList.push({ value: e.no, label: e.name, id: e.id })
        }
        if (e.name == this.operator) {
          this.customerId = e.id
          this.shopNo = e.no
          this.shopName = e.name
          this.getInfo()
        }
      })
    })
  },
  components: {
    footView,
    newVs
  },
  data() {
    return {
      shopNo: '',
      shopName: '',
      shopList: [],
      inpList: [],
      isRegular: false,
      affirm: null,
      confirmList: [
        { label: '全部', value: null },
        { label: '未确认', value: 0 },
        { label: '已完成', value: 1 }
      ],
      title: '',
      title1: '',
      showNew: false,
      Dis: false,
      jxQuarter: null,
      operator: null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1],
      // operator: document.cookie.match(RegExp('jxUser' + '=([^;]+)'))[1],
      jxStore: this.getCookie('jxStore') == '1',
      allData: [],
      //数据总条数
      dataLen: 0,
      //总页码数
      pagesNum: 0,
      //每页显示条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      saveList: [],
      showbox: 'none',
      Howmany: '',
      aList: [],
      cList: [],
      main: '',
      minor: '',
      List: [],
      List1: [],
      kindsNumber: '',
      brandedName: '',
      brandedList: [],
      timeData: '',
      bList: [],
      checked: false,
      vip: '',
      vipPhone: null,
      vipList: [],
      bList1: [
        // {prop:'settleAccounts',label:'已结账',width:'100'},
        // {prop:'affirm',label:'已确认',width:'80'},
        { prop: 'vipSellSequence', label: '单号', width: '130' },
        { prop: 'sellTime', label: '日期', width: '160' },
        { prop: 'number', label: '数量' },
        { prop: 'money', label: '金额' },
        { prop: 'preferential', label: '抹零' },
        { prop: 'exchange', label: '兑换' },
        { prop: 'payg', label: '收现' },
        { prop: 'main', label: '主推' },
        { prop: 'minor', label: '次推' },
        { prop: 'integralNumber', label: '积分' },
        { prop: 'integralMoney', label: '积分额' },
        { prop: 'remark', label: '备注' }
      ],

      eList: [],
      eList1: [
        { prop: 'operator', label: '店铺', width: '120' },
        { prop: 'vip', label: 'VIP', width: '120' },
        { prop: 'kindsNumber', label: '款号', width: '140' },
        { prop: 'colorName', label: '颜色' },
        { prop: 'size', label: '尺码编号' },
        { prop: 'number', label: '数量' },
        { prop: 'sellPrice', label: '售价' },
        { prop: 'discount', label: '折数' },
        { prop: 'onePrice', label: '单价' },
        { prop: 'money', label: '金额' },
        { prop: 'commodityName', label: '品名', width: '160' },
        { prop: 'brandeName', label: '品牌' }
      ],
      eList2: [
        { prop: 'typeNumber', label: '型号', width: '120' },
        { prop: 'colorName', label: '颜色' },
        { prop: 'c05', label: '05-XS' },
        { prop: 'c07', label: '07-S' },
        { prop: 'c09', label: '09-M' },
        { prop: 'c11', label: '11-L' },
        { prop: 'c13', label: '13-XL' },
        { prop: 'c15', label: '15-2L' },
        { prop: 'c17', label: '17-3L' },
        { prop: 'c19', label: '19-4L' },
        { prop: 'c21', label: '21-5L' },
        { prop: 'c23', label: 'C23', width: '' },
        // {prop:'f',label:'D'},
        { prop: 'f', label: 'F' },
        { prop: 'subtotal', label: '小计' },
        { prop: 'sellingPrice', label: '售价' }
      ],
      vipSellSequence: '',
      twoList: [],
      clerkList: [],
      sendData: {},
      det: {}
    }
  },
  methods: {
    saveNew() {},
    dbClick(e) {
      console.log(e)
      if (e.settleAccounts == '未结账' && this.jxStore) {
        this.title = '编辑'
        if (e.affirm == '已确认') {
          this.title1 = '00'
        } else {
          this.title1 = '11'
        }

        this.showNew = true
        this.sendData = {}
        this.sendData = e
        this.clerkList = []
        if (!this.checked) {
          for (let r of this.saveList) {
            if (e.vipSellSequence == r.vipSellSequence) {
              this.clerkList.push(r)
            }
          }
        }
      }
      // console.log(this.clerkList)
    },

    Confirm() {
      if (this.vipSellSequence == '') {
        this.$message.warning({ message: '请选中一条数据确认', offset: 400 })
        return
      }
      confirm({
        vipSellSequence: this.vipSellSequence,
        accountType: Number(!this.jxStore)
      }).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.$message.success({ message: '确认成功', offset: 400 })
          this.query()
        }
      })
    },
    Del() {
      // this.tableData1.splice(this.det.xh-1,1)
      if (JSON.stringify(this.det).replace(/\{|}/g, '') == '') {
        this.$message.warning({ message: '请选择一条删除' })
        return
      }
      for (let r of [this.det]) {
        for (let k of [this.det]) {
          k.sellTime = k.sellTime + ' 00:00:00'
        }
        if (r.settleAccounts == '未结账') {
          r.settleAccounts = 0
        }
        if (r.affirm == '未确认') {
          r.affirm = 0
        }
      }
      this.$confirm('是否删除本条的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.det)
          DeleteSell(this.det).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message.success({ message: '删除成功' })
              this.query()
            } else {
              this.$message.error({ message: '删除失败' })
              for (let t of [this.det]) {
                if (t.settleAccounts == 0) {
                  t.settleAccounts = '未结账'
                }
                if (t.affirm == 0) {
                  t.affirm = '未确认'
                }
                t.sellTime = t.sellTime.slice(0, 10)
              }
            }
          })
        })
        .catch(() => {
          for (let t of [this.det]) {
            if (t.settleAccounts == 0) {
              t.settleAccounts = '未结账'
            }
            if (t.affirm == 0) {
              t.affirm = '未确认'
            }
            t.sellTime = t.sellTime.slice(0, 10)
          }
        })
    },
    //补单
    Supplement() {
      console.log(JSON.stringify([this.det]))
      if (this.detail == '') {
        this.$message.warning({ message: '请选择一条数据补单' })
        return
      }
      // if(this.jz == '已结账'){
      //   this.$message.warning({message:'此单已结账，不可补单'})
      //   return
      // }
      this.title = '补单'
      this.showNew = true
    },

    rowClick(e) {
      this.detail = [e]
      this.det = e
      this.sendData = e
      this.clerkList = []

      if (e.affirm == 1 || e.affirm == '已确认') {
        this.Dis = true
      } else {
        this.Dis = false
      }
      this.vipSellSequence = e.vipSellSequence
      this.cList = []
      if (this.checked == false) {
        this.saveList.forEach((el) => {
          console.log(el, 'el')
          if (e.vipSellSequence == el.vipSellSequence) {
            el.operator = e.operator
            this.cList.push(el)
            this.clerkList.push(el)
          }
        })
      } else {
        this.twoList.forEach((el) => {
          if (e.vipSellSequence == el.vipSellSequence) {
            this.cList.push(el)
          }
        })
      }
    },
    Change1() {
      for (let a of this.vipList) {
        if (this.vipPhone == a.value) {
          this.vip = a.value1
        }
      }
    },
    //导出
    exportExcel() {
      let obj = {
        main: this.main,
        minor: this.minor,
        kindsNumber: this.kindsNumber,
        brandedName: this.brandedName,
        vip: this.vip,
        startTime:
          this.timeData == null
            ? ''
            : this.timeData[0].slice(0, 10) + ' 00:00:00',
        endTime:
          this.timeData == null
            ? ''
            : this.timeData[1].slice(0, 10) + ' 23:59:59',
        accountType: Number(!this.jxStore),
        directSaleNo: this.shopNo
      }
      getShopSale(obj).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.$nextTick(() => {
            this.exp('店铺销售')
            // this._getStock({limit:this.limit,page:this.currentPage})
          })
        }
      })
    },
    query() {
      let obj = {
        affirm: this.affirm,
        main: this.main,
        minor: this.minor,
        kindsNumber: this.kindsNumber,
        brandedName: this.brandedName,
        vip: this.vip,
        startTime:
          this.timeData == null
            ? ''
            : this.timeData[0].slice(0, 10) + ' 00:00:00',
        endTime:
          this.timeData == null
            ? ''
            : this.timeData[1].slice(0, 10) + ' 23:59:59',
        accountType: Number(!this.jxStore),
        directSaleNo: this.shopNo
      }
      // console.log(obj)
      getShopSale(obj).then((res) => {
        // console.log(res.data)
        if (res.data.data != null) {
          for (let a of res.data.data.total) {
            if (a.settleAccounts == 0) {
              a.settleAccounts = '未结账'
            } else {
              a.settleAccounts = '已结账'
            }
            if (a.affirm == 0) {
              a.affirm = '未确认'
            } else {
              a.affirm = '已确认'
            }
          }
          // this.aList = []
          this.allData = []
          res.data.data.total.forEach((e) => {
            e.accountType = Number(!this.jxStore)
            if (e.recharge == 0) {
              // this.aList.push(e)
              this.allData.push(e)
            }
          })
          // console.log(this.allData, 'queryqueryquery')
          this.dataLen = this.allData.length
          // this.aList = this.allData.slice(
          //   (this.currentPage - 1) * this.limit,
          //   this.currentPage * this.limit
          // )
          this.aList = res.data.data.info
          console.log(this.aList)
          this.saveList = res.data.data.info
          this.twoList = res.data.data.twoInfoList
        } else {
          this.pagesNum = 0
          this.currentPage = 1
          this.dataLen = 0
          this.aList = []
          this.cList = []
        }
      })

      if (this.vip != '' && this.jxStore) {
        getmoney({
          vip: this.vip,
          accountType: Number(!this.jxStore)
        }).then((res) => {
          // console.log(res.data.data, 'res.data.data.balance')
          this.showbox = 'block'
          // this.Howmany = res.data.data.balance
          this.Howmany = res.data.data.info
        })
      }
    },
    //指定列和计
    getList(param) {
      // console.log(this.zt)
      if (this.zt == 'null') {
        return
      } else {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const values = data.map((item) => Number(item[column.property]))
          if (
            column.property === 'number' ||
            column.property === 'money' ||
            column.property === 'preferential' ||
            column.property === 'payg' ||
            column.property === 'exchange'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index]
          }
        })
        return sums
      }
    },
    handleSizeChange(val) {
      //每页多少条
      this.limit = val
      //总页码
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
      this.query()
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val
      this.query()
    },

    shopChange(e) {
      this.shopNo = e
      this.getInfo()
    },

    getInfo() {
      this.vipList = []
      this.List = []
      this.List1 = []

      if (this.shopNo) {
        //vip
        getVip({
          directSaleNo: this.shopNo,
          accountType: Number(!this.jxStore)
        }).then((res) => {
          res.data.data.forEach((e) => {
            this.vipList.push({ value: e.name, label: e.name, value1: e.phone })
          })
        })

        //主推 次推
        getClerk1({
          directSaleNo: this.shopNo,
          accountType: Number(!this.jxStore)
        }).then((res) => {
          console.log(res)
          res.data.data.forEach((e) => {
            this.List.push({
              value: e.personnelNo,
              label: e.personnelNo,
              value1: e.personnelName
            })
            this.List1.push({
              value: e.personnelNo,
              label: e.personnelNo,
              value1: e.personnelName
            })
          })
        })
      }
    }
  },
  watch: {
    kindsNumber(a, b) {
      if (a != undefined) {
        this.kindsNumber = a.toUpperCase().trim()
      }
    },
    checked(a, b) {
      if (a) {
        this.eList = this.eList2
        if (this.cList != '') {
          var nList = []
          for (let c of this.twoList) {
            // console.log(c.vipSellSequence)
            if (this.vipSellSequence == c.vipSellSequence) {
              nList.push(c)
            }
            this.cList = nList
          }
        }
      } else {
        this.eList = this.eList1
        if (this.cList != '') {
          var mList = []
          for (let c of this.saveList) {
            if (this.vipSellSequence == c.vipSellSequence) {
              mList.push(c)
            }
            this.cList = mList
          }
        }
      }
    },
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    limit(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    }
  }
}
</script>
<style scoped>
.storeSalesQuery {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 92.5vh;
  position: relative;
}
.ssq-top {
  padding: 15px 0;
  border-bottom: 2px solid #f4f4f4;
}
.ssq-top div {
  display: flex;
}
.ssq-top p {
  margin-right: 10px;
  display: inline-block;
  white-space: nowrap;
  width: 80px;
  text-align: end;
}
.wd {
  width: 160px;
}
.ssq-btn {
  padding: 15px 15px;
  display: flex;
  justify-content: space-between;
}
.ssq-tab {
  display: flex;
}
.tab-left {
  width: 55%;
  padding-right: 5px;
  border-right: 2px solid #f4f4f4;
}
.tab-right {
  width: 45%;
  padding-left: 5px;
}
.balance {
  padding: 5px;
  background: #f5f7fa;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
.tip {
  border: 1px;
  border-radius: 50%;
  width: 13px;
  height: 13px;
  margin: 6px 5px 0 5px;
}
.tip1 {
  border: 1px;
  border-radius: 50%;
  width: 13px;
  height: 13px;
  margin: 6px 1px 0 4px;
}
</style>

<style>
.storeSalesQuery .ssq-top .el-input__inner,
.storeSalesQuery .ssq-btn .el-input__inner {
  height: 30px;
}
.storeSalesQuery .ssq-top .el-date-editor .el-range__icon {
  line-height: 23px;
}
.storeSalesQuery .ssq-top .el-date-editor .el-range-separator {
  width: 8%;
  line-height: 23px;
}
.storeSalesQuery .ssq-btn .el-checkbox.is-bordered {
  padding: 5px 20px 9px 10px;
  height: 30px;
}
.storeSalesQuery .el-checkbox.is-bordered {
  padding: 5px 10px 0 10px;
  height: 30px;
}
.storeSalesQuery .el-date-editor--daterange.el-input,
.el-date-editor--daterange.el-input__inner,
.el-date-editor--timerange.el-input,
.el-date-editor--timerange.el-input__inner {
  width: 280px;
}

.storeSalesQuery .ssq-top .el-input__inner {
  padding: 0 5px;
}
</style>
